package com.university.mentalhealthplatform.studentV3.ai.jimmer;


import com.university.mentalhealthplatform.global.rbac.jwt.JwtUtils;
import com.university.mentalhealthplatform.global.rbac.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.servlet.http.HttpServletRequest;

import java.util.UUID;

@Component
public class BaseEntityDraftInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest request;

    @PrePersist
    public void prePersist(BaseEntity entity) {
        String token = getTokenFromRequest();
        String userId = jwtUtils.extractUsername(token);
        User user = new User();
        user.setId(UUID.fromString(userId));
        entity.setCreator(user);
        entity.setEditor(user);
    }

    @PreUpdate
    public void preUpdate(BaseEntity entity) {
        String token = getTokenFromRequest();
        String userId = jwtUtils.extractUsername(token);
        User user = new User();
        user.setId(UUID.fromString(userId));
        entity.setEditor(user);
    }

    private String getTokenFromRequest() {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new IllegalArgumentException("无效的Token");
    }
}